<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { toNumber } from 'lodash-es'
import qs from 'qs'
import type { FormType } from './index.ts'
import { GetDetailData, IdGetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/memberproduct'
import { GetAllData } from '@/api/modules/merchandiseControl'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

// const imgDomain = 'https://img1.eprhan.cc'

const ruleFormRef = ref<FormInstance>()
const id = route.query.id as string
const productId = route.query.productId as string
const type = route.query.type as string
// 判断是秒杀还是积分
const formType = ref(0)
// 判断是编辑还是新增
let setDataSwitch = true

const ruleForm = ref<FormType>({
  productId: productId !== undefined ? toNumber(productId) : 0,
  payType: 1,
  saleScore: 0,
  secTime: '',
  secEndTime: '',
  secLabels: '',
  id: '',
})

const templateTypeOptionList = ref([
  {
    value: 1,
    label: '兑换',
  },
  {
    value: 2,
    label: '组合',
  },
])

const labelsArr = ref<string[]>(['', ''])

interface optionType {
  productId: number
  productName: string
  cdnProductPhotoPic: string
  flag: number
}
const options = ref<optionType[]>([])

// 提交
async function SubmitData() {
  const params = ruleForm.value
  params.secLabels = labelsArr.value.join(',')
  if (formType.value === 2) {
    // 不是秒杀商品时清空秒杀标签
    params.secLabels = ''
    delete params.secEndTime
    delete params.secTime
  }
  else {
    // 秒杀商品不编辑开始时间
    // params.secTime = ''
    delete params.secTime
  }
  // if (params.payType !== 2 && (params.saleScore === 0 || params.saleScore < 0)) {
  //   ElMessage.error('请输入正确的积分')
  //   return 0
  // }
  if (id || setDataSwitch) {
    // 编辑
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'memberproductIndex' })
      }
      else {
        ElMessage.error(`编辑失败${res.errors}`)
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyMemberproduct()
        router.push({ name: 'memberproductIndex' })
      }
      else {
        ElMessage.error(`编辑失败${res.errors}`)
      }
    })
  }
}

watch(ruleForm, (newValue) => {
  if (!id && !productId) {
    detailData.RememberMemberproduct(newValue)
  }
}, { deep: true })

watch(() => ruleForm.value.productId, (newProductId) => {
  const option = options.value.find(option => option.productId === newProductId)
  formType.value = option ? option.flag : 0
  // console.log(formType.value)
}, { deep: true })

onMounted(async () => {
  const FlagList: any = qs.stringify({ FlagList: [2, 3, 4] })
  await GetAllData(FlagList).then((res: any) => {
    options.value = res.data
    ruleForm.value.productId = toNumber(productId)
  })
  if (id) {
    await GetDetailData(id).then(async (res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        labelsArr.value = res.data.secLabels.split(',')
      }
    })
  }
  else if (productId) {
    await IdGetDataDetail({ productId }).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        labelsArr.value = res.data.secLabels.split(',')
        // res.data.productFlag === 3 ? formType.value = true : formType.value = false
      }
      else if (res.errors === '记录不存在') {
        const option = options.value.find(option => option.productId === toNumber(productId))
        formType.value = option ? option.flag : 0
        setDataSwitch = false
      }
    })
  }
  else {
    // 获取缓存数据
    ruleForm.value = detailData.GetMemberproduct()
    // 拆分秒杀标签的两个
    labelsArr.value = detailData.GetMemberproduct().secLabels.split(',')
  }
})
</script>

<template>
  <div>
    <PageHeader :title="type ? type === '1' ? '编辑' : '添加' : id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="绑定商品">
              <el-select
                v-model="ruleForm.productId"
                :disabled="!!(productId || id)"
                filterable
                placeholder="Select"
                style="max-width: 400px;"
              >
                <el-option
                  v-for="item in options"
                  :key="item.productId"
                  :label="`${item.productId}-${item.productName}`"
                  :value="item.productId"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="formType !== 2" :md="16">
            <ElFormItem label="秒杀标签">
              <ElCol :md="12">
                <el-input v-model="labelsArr[0]" style="width: 400px;" placeholder="请输入秒杀标签" />
              </ElCol>
              <ElCol :md="12">
                <el-input v-model="labelsArr[1]" style="width: 400px;" placeholder="请输入秒杀标签" />
              </ElCol>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="formType !== 4" :md="8">
            <ElFormItem label="积分数量">
              <el-input v-model="ruleForm.saleScore" style="width: 400px;" placeholder="请输入积分数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="支付类型">
              <el-select v-model="ruleForm.payType" placeholder="请选择支付类型" style="width: 400px;" clearable>
                <el-option v-for="items in templateTypeOptionList" :key="items.value" :label="items.label" :value="items.value" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="秒杀开始时间">
              <el-date-picker
                v-model="ruleForm.secTime"
                type="datetime"
                placeholder="请选择时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol> -->
          <ElCol v-if="formType !== 2" :md="8">
            <ElFormItem label="秒杀结束时间">
              <el-date-picker
                v-model="ruleForm.secEndTime"
                type="datetime"
                placeholder="请选择时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
